package com.yaolaizaixian.merchant.order;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.victor.loading.rotate.RotateLoading;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.adapter.QuanYiAdapter;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.Customer;
import com.yaolaizaixian.merchant.bean.Discount;
import com.yaolaizaixian.merchant.bean.MemberInfo;
import com.yaolaizaixian.merchant.bean.MemberInfoModel;
import com.yaolaizaixian.merchant.bean.QuanyiInfo;
import com.yaolaizaixian.merchant.bean.RightsDetail;
import com.yaolaizaixian.merchant.bean.RightsDetailInfo;
import com.yaolaizaixian.merchant.home.QunyiErweimaActivity;
import com.yaolaizaixian.merchant.utils.BusinessUtils;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.MyUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.Call;

/**
 * 会员查询结果界面
 */
public class QueryResultActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "QueryResultActivity";
    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.ll_ref)
    AutoLinearLayout llRef;
    @BindView(R.id.xrv_orderlist)
    XRecyclerView xrvOrderlist;
    @BindView(R.id.rl_saoyisao)
    AutoRelativeLayout rlSaoyisao;
    private TextView tv_address;
    private TextView tvTitleText;
    private TextView tv_username;
    private TextView tv_userno;
    private TextView tv_usergrade;
    private TextView tv_userstatus;
    private XRecyclerView xrv_orderlist;
    private TextView tv_query_result;
    private RelativeLayout rl_saoyisao;
    private List<Discount> discounts;
    private String codetype;
    //可用金币数量
    private Double validcoin = 0.00;
    private String phone;
    private RotateLoading rotateloading;
    //是否接受预定服务
    private String lb = "是";
    private String customerId = "";
    private RelativeLayout rl_queryresult_benefit;
    private String usergrade = "";
    private MaterialDialog mMaterialDialog;
    private List<RightsDetailInfo> erList;
    private QuanYiAdapter  quanYiAdapter;
    //权益码
    private String code="";
    //店铺ID
    private String shopsysno="";
    //销售员ID
    private String usersysno="";
    //客户的会员等级
    private int customerLevel=0;
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {
                        MemberInfoModel memberInfoModel = GsonUtil.jsonToBean(result, MemberInfoModel.class);
                        MemberInfo memberInfo = memberInfoModel.getData();
                        Customer customer = memberInfo.getCustomer();
                        customerId = customer.getSysno();

                        if (null != customer) {

                            if (!TextUtils.isEmpty(customer.getCustomername())) {

                                tv_username.setText(customer.getCustomername().substring(0, 1) + "先生/女士");
                            }
                            else {

                                tv_username.setText(customer.getCustomerid().substring(0, 3) + "****" + customer.getCustomerid().substring(7));
                            }

                            tv_userno.setText(customer.getCardNumber());
                            validcoin = customer.getValidcoin();

                            customerLevel=customer.getCustomerrank();
                            //会员等级
                            usergrade= BusinessUtils.getCustomerRank(customer.getCustomerrank());
                            tv_usergrade.setText(BusinessUtils.getCustomerRank(customer.getCustomerrank()));

                            //金币返利
                            if (!TextUtils.isEmpty(memberInfo.getCoinrebatesrate())) {

                                tv_query_result.setText(usergrade + "      尊享金币返利" + memberInfo.getCoinrebatesrate() + "%");
                            }
                            else {

                                tv_query_result.setText(usergrade + "     尊享金币返利0%");
                            }

                            //会员状态判断
                            if (customer.getCustomerstatus() == 0) {
                                tv_userstatus.setText("正常");
                            } else if (customer.getCustomerstatus() == -1) {
                                tv_userstatus.setText("停封");
                            } else if (customer.getCustomerstatus() == -2) {
                                tv_userstatus.setText("锁定");
                            }
                            //店铺名称
                            String shopAddress = SharedPreferencesUtil.getString(getApplicationContext(), "Shopname", " ");
                            tv_address.setText(shopAddress);

                            //获取用户在当前店铺的权益列表
                            getRightsList();
                            rl_saoyisao.setVisibility(View.VISIBLE);

                        }
                    } else {

                        dissmiss();

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            showConflictDialog(QueryResultActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(QueryResultActivity.this, "您的账号在其它设备登录");

                        } else {
                            Toasty.error(getApplicationContext(), baseModel.getErrorMsg(), Toast.LENGTH_SHORT).show();
                            return;
                        }

                    }
                    break;

                //使用权益
                case 2:

                    String result2 = (String) msg.obj;
                    LogUtil.e(TAG, "权益使用成功：" + result2);
                    BaseModel baseModel2 = GsonUtil.jsonToBean(result2, BaseModel.class);

                    if (baseModel2.isFlag()) {

                        mMaterialDialog.dismiss();
                        Toasty.success(getApplicationContext(), "权益使用成功", Toast.LENGTH_SHORT).show();
                        //刷新权益列表
                        erList.clear();
                        getRightsList();

                        dissmiss();

                    } else {


                        dissmiss();
                        mMaterialDialog.dismiss();
                        Toasty.error(getApplicationContext(), baseModel2.getErrorMsg(), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    break;

                //获取权益列表
                case 4:

                     String result4 = (String) msg.obj;
                     BaseModel baseModel3 = GsonUtil.jsonToBean(result4, BaseModel.class);
                     LogUtil.LogShitou(TAG, result4);

                     if (baseModel3.isFlag())
                     {
                         RightsDetail rightsDetail = GsonUtil.jsonToBean(result4, RightsDetail.class);
                         erList = rightsDetail.getData().getErList();
                         quanYiAdapter = new QuanYiAdapter(QueryResultActivity.this, erList);
                         xrv_orderlist.setAdapter(quanYiAdapter);
                         dissmiss();

                     }else
                     {
                         dissmiss();
                     }

                    break;

                //权益详情
                case 5:

                    String result5 = (String) msg.obj;
                    Log.e(TAG,"权益详情"+result5);
                    BaseModel baseModel5 = GsonUtil.jsonToBean(result5, BaseModel.class);
                    if (baseModel5.isFlag())
                    {
                        QuanyiInfo quanyiInfo = GsonUtil.jsonToBean(result5, QuanyiInfo.class);
                        showdia(quanyiInfo.getData().getEr().getName());
                        dissmiss();
                    }
                    else
                    {
                        dissmiss();
                        Toasty.error(getApplicationContext(), baseModel5.getErrorMsg(), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    break;
            }
        }
    };


    @Override
    public void initView() {

        setContentView(R.layout.activity_query_result);

    }

    @Override
    public void initData() {

        rotateloading = (RotateLoading) findViewById(R.id.rotateloading);
        Intent intent = getIntent();

         phone = intent.getStringExtra("phone");
         //店铺ID
         shopsysno = SharedPreferencesUtil.getString(getApplicationContext(), "shopsysno", "");
         //销售员ID
         usersysno = SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", "");

        //1手机号 2卡号
        // codetype=intent.getStringExtra("codetype");
        LinearLayoutManager layoutManager = new LinearLayoutManager(QueryResultActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        discounts = new ArrayList<>();
        xrv_orderlist = (XRecyclerView) findViewById(R.id.xrv_orderlist);
        tvTitleText = (TextView) findViewById(R.id.tv_title_text);
        LinearLayout ll_back = (LinearLayout) findViewById(R.id.ll_back);
        ll_back.setOnClickListener(this);
        LinearLayout ll_ref = (LinearLayout) findViewById(R.id.ll_ref);
        ll_ref.setOnClickListener(this);
        rl_saoyisao = (RelativeLayout) findViewById(R.id.rl_saoyisao);
        rl_saoyisao.setOnClickListener(this);
        xrv_orderlist.setLayoutManager(layoutManager);
        xrv_orderlist.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrv_orderlist.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        xrv_orderlist.setArrowImageView(R.mipmap.iconfont_downgrey);
        xrv_orderlist.setPullRefreshEnabled(false);
        xrv_orderlist.setLoadingMoreEnabled(false);
        View header = LayoutInflater.from(this).inflate(R.layout.head_discount, (ViewGroup) findViewById(android.R.id.content), false);
        tv_address = (TextView) header.findViewById(R.id.tv_address);
        tv_username = (TextView) header.findViewById(R.id.tv_username);
        tv_userno = (TextView) header.findViewById(R.id.tv_userno);
        tv_usergrade = (TextView) header.findViewById(R.id.tv_usergrade);
        tv_userstatus = (TextView) header.findViewById(R.id.tv_userstatus);
        tv_query_result = (TextView) header.findViewById(R.id.tv_query_result);
        rl_queryresult_benefit = (RelativeLayout) header.findViewById(R.id.rl_queryresult_benefit);
        xrv_orderlist.addHeaderView(header);
        tvTitleText.setText("会员权益查询结果");
        showloading();
        //获取用户基本信息
        getData(phone);

    }


    private void dissmiss() {

        if (rotateloading.isStart()) {
            rotateloading.stop();
        }
    }

    private void showloading() {

        rotateloading.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    //获取会员信息接口
    private void getData(String phone) {

        //店铺id
        final String url = BaseInfo.URL + "customerInfo/info.do";
        HashMap<String, String> sortedParams = new HashMap<String, String>();
        // sysNo 值  3des加密
        sortedParams.put("cardNumber", phone);
        sortedParams.put("shopStoreSysno", shopsysno);
        LogUtil.e(TAG, "店铺ID" + shopsysno);
        //权益类型：1抵扣 2抵用
        sortedParams.put("equityRuleType", "2");
        OkHttpUtils
                .post()
                .url(url)
                .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                .build()
                .execute(new MyStringCallback(1));
    }


    //使用优惠
    public void userDiscount(String code) {

        final String url = BaseInfo.URL + "equityController/shopAuditUseEquityrule.do";
        HashMap<String, String> sortedParams = new HashMap<String, String>();
        sortedParams.put("code", code);
        sortedParams.put("shopStoreSysno", shopsysno);
        sortedParams.put("customerSysno", customerId);
        sortedParams.put("employeeSysno", usersysno);
     /*   sortedParams.put("code", "13246722");
        sortedParams.put("shopStoreSysno", "86");
        sortedParams.put("customerSysno", "32808");
        sortedParams.put("employeeSysno", "133");*/
        OkHttpUtils
                .post()
                .url(url)
                .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                .build()
                .execute(new MyStringCallback(2));
    }



    //获取用户抵用权益列表
    private void getRightsList() {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();
            final String url = BaseInfo.URL + "equityController/searchList.do";

            //店铺id
            sortedParams.put("shopStoreSysno", shopsysno);
            //客户的会员等级
            sortedParams.put("customerLevel", String.valueOf(customerLevel));
            //客户id
            sortedParams.put("customerSysno", customerId);
            //类型
            sortedParams.put("type", "2");

//            sortedParams.put("shopStoreSysno", "86");
//            sortedParams.put("customerLevel", "200");
//            sortedParams.put("customerSysno", customerId);
//            sortedParams.put("type", "2");

            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, this))
                    .build()
                    .execute(new MyStringCallback(4));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_back:

                finish();

                break;

            //扫一扫界面
            case R.id.rl_saoyisao:


                if (Build.VERSION.SDK_INT >= 23) {
                    PackageManager packageManager = getPackageManager();
                    int permission = packageManager.checkPermission("android.permission.CAMERA", this.getPackageName());
                    if (PackageManager.PERMISSION_GRANTED == permission) {


                        Intent intent=new Intent(this, QunyiErweimaActivity.class);
                        //获取订单二维码
                        startActivityForResult(intent, 108);

                    } else {
                        //没有这个权限
                        Toasty.error(getApplicationContext(), "请在应用设置界面打开本应用照相机权限", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (MyUtils.cameraIsCanUse()) {

                        Intent intent=new Intent(this, QunyiErweimaActivity.class);
                        //获取订单二维码
                        startActivityForResult(intent,108);

                    } else {
                        Toasty.error(getApplicationContext(), "请在应用设置界面打开本应用照相机权限", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
        }

    }

    //获取权益详情
    public void getQuanyiInfo(String code) {

        //店铺id
        final String url = BaseInfo.URL + "equityController/equityRuleInfoByCode.do";
        HashMap<String, String> sortedParams = new HashMap<String, String>();
        sortedParams.put("code", code);
        sortedParams.put("customerSysno", customerId);

        Log.e(TAG,"CODE="+code+",customerSysno="+customerId);

        //sortedParams.put("customerSysno", "32808");
        OkHttpUtils
                .post()
                .url(url)
                .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                .build()
                .execute(new MyStringCallback(5));
    }


    class MyStringCallback extends StringCallback {

        private int mhandlercode=0;

        private  MyStringCallback(int handlercode)
        {
            this.mhandlercode=handlercode;
        }

        @Override
        public void onError(Call call, Exception e, int id) {


            Log.e(TAG,"结果"+e.toString());
            dissmiss();

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = mhandlercode;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK

            case 108:


                Bundle b=data.getExtras(); //data为B中回传的Intent

                String mcode=b.getString("code");//str即为回传的值

                Log.e(TAG,mcode);

                code=mcode;
                //获取权益详情
                getQuanyiInfo(code);

                break;


            default:


                break;
        }
    }



    public void showdia(String  titile)
    {
        mMaterialDialog = new MaterialDialog(QueryResultActivity.this);
        mMaterialDialog.setMessage("是否使用"+titile+"?");
        mMaterialDialog.setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用当前权益
                userDiscount(code);
            }
        });

        mMaterialDialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mMaterialDialog.dismiss();
            }
        });
        mMaterialDialog.show();
    }

}


